export const empty = ooo => {
  Object.keys(ooo).forEach(key => {
    ooo[key] = null
  })
}

export const emptyIf = ooo => {
  Object.keys(ooo).forEach(key => {
    if (ooo[key] === '') ooo[key] = null
  })
}
export const promise = function ({
  fn,
  target,
  nodejs = true,
  last = true
}) {
  return (...args) => {
    // eslint-disable-next-line no-undef
    return new Promise((resolve, reject) => {
      args[last === true ? 'push' : 'unshift']((err, ...data) => {
        if (nodejs === false) {
          const result = [err, ...data]
          if (result.length > 1) {
            return resolve.call(this, [err, ...data])
          } else {
            return resolve.apply(this, [err, ...data])
          }
        } else if (err === null || err === undefined) {
          if (data.length > 1) {
            return resolve.call(this, data)
          } else {
            return resolve.apply(this, data)
          }
        } else {
          return reject(err)
        }
      })
      if (target) {
        fn.apply(target, args)
      } else {
        fn.apply(null, args)
      }
    })
  }
}

export const sleep = function (time) {
  // eslint-disable-next-line no-undef
  return new Promise(resolve => setTimeout(resolve, time))
}

export const randomArray = function (arr) {
  const arrs = arr.filter(item => !!item)
  let N = arrs.length
  if (N > 0) {
    let index = Math.floor(Math.random() * N)
    return arrs[index]
  }
}

export const format = function (temp, ...args) {
  if (args.length === 0) return temp.replace(/\{(\w+)\}/g, '')
  else if (args.length !== 1 || typeof args[0] !== 'object') {
    return temp.replace(/\{(\w+)\}/g, function (m, i) {
      return args[i] || args[0]
    })
  } else {
    return temp.replace(/\{([^}]+)\}/g, function (m, i) {
      return args[0][i]
    })
  }
}

export const clone = function (o) {
  let clone = {}
  for (let p in o) clone[p] = o[p]
  return clone
}
export const merge = function (target, src) {
  for (let p in src) {
    if (typeof src[p] === 'object') {
      if (src[p].join) {
        target[p].splice(0, target[p].length, ...src[p])
      } else {
        merge(target[p], src[p])
      }
    } else {
      target[p] = src[p]
    }
  }
}

const reg = new RegExp('^/')
export const go = function (path, that) {
  const split = reg.test(path) ? '' : '/'
  window.location.assign(`${window.location.origin}${split}${path}`)
}
/**
 *
 * @desc   判断`obj`是否为空
 * @param  {Object} obj
 * @return {Boolean}
 */
export const isEmptyObject = function (obj) {
  if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return false
  return !Object.keys(obj).length
}
